import requests,json



class Baidu():
    def __init__(self):
        self.API_KEY = "2ULc96JZMrAcmjlsoUwlq6jO"
        self.SECRET_KEY = "C5mmsFifhcAERAYRTibbtu3XjAnF5zII"

    def idcard(self, url_img):
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()

        payload = 'id_card_side=front&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false&detect_screenshot=false'%(url_img)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        print(response.text)
        return json.loads(response.text)



    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))


idcard = Baidu()